package hkyg.background.controller;

import hkyg.background.model.GeBytearray;
import hkyg.background.service.BackgroundService;
import hkyg.util.HkygUtil;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;


@Controller
@RequestMapping("hkyg")
public class BackgroundController {
	@Autowired
	private BackgroundService backService;

	@RequestMapping(value="/Background.do",method=RequestMethod.POST)
	@ResponseBody 
	public Map<String,Object> addUserInfo(HttpServletRequest request,HttpServletResponse response) throws Exception{
		return HkygUtil.dispatch(request,response,backService);
	}
	
	@RequestMapping(value="/getNews.do",method=RequestMethod.POST)
	@ResponseBody 
	public Map<String,Object> getNews(HttpServletRequest request,HttpServletResponse response) throws Exception{
		return HkygUtil.dispatch(request,response,backService);
	}
	/**
	 * 上传文件到数据仓库
	 * @param request
	 * @param response
	 * @return String
	 * @throws Exception
	 */
	
	@RequestMapping(value="/uploadFile.do",method=RequestMethod.POST)
	public @ResponseBody String uploadFile(HttpServletRequest request,HttpServletResponse response ) throws Exception {
		
		   String responseStr;	
		   try {
				     DiskFileUpload fu = new DiskFileUpload();
				     // 设置允许用户上传文件大小,单位:字节，这里设为2m
				     fu.setSizeMax(2*1024*1024);
					 // 设置最多只允许在内存中存储的数据,单位:字节
					 fu.setSizeThreshold(4096);
					 // 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
					 //开始读取上传信息
					 List<FileItem> fileItems = fu.parseRequest(request);
					 // 依次处理每个上传的文件
				     Iterator<FileItem> iter = fileItems.iterator();

				     iter.next();
				     FileItem item = (FileItem)iter.next();
	        
//					MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
//					MultipartFile file = req.getFile("file");
//					String type = file.getContentType();
//					String attachmentName = file.getOriginalFilename();
				    String type = item.getContentType();
					String attachmentName = item.getName();
					String pg_type = request.getParameter("pg_type");
					GeBytearray byteArray = new GeBytearray();
					
					byteArray.setPg_type(pg_type);
//					byteArray.setPg_bytes(file.getBytes());
					byte[] b = new byte[1024*1024*3];
					item.getInputStream().read(b);
					byteArray.setPg_bytes(b);
					byteArray.setPg_name(attachmentName);
					
					backService.addGeBytearray(byteArray);
					int pg_id = byteArray.getPg_id();
					//返回pg_id、type给客户端
					responseStr = "{success: true, ajaxErrorCode: 200, " 
						+ "name: \'" + attachmentName + "\', type: \'" + type + "\', pg_id: \'" + pg_id + "\'}";
					return responseStr;
		}catch(Exception e){
			e.printStackTrace();
			responseStr = "{success: false}";
			return responseStr;

		}

	}
	/**
	 * 下载任务相关附件
	 * @param request
	 * @param response
	 * @return void
	 * @throws Exception
	 */
	
	@RequestMapping(value="/downloadFile.do",method=RequestMethod.GET)
	public @ResponseBody void downloadAttachment(HttpServletRequest request,HttpServletResponse response ) throws Exception {
		
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			
				int pg_id = Integer.parseInt(request.getParameter("pg_id"));
				GeBytearray byteArray = backService.getGeBytearray(pg_id);
				InputStream is = new ByteArrayInputStream(byteArray.getPg_bytes());
				String name = byteArray.getPg_name();
				name = new String(name.getBytes("GB2312"), "ISO-8859-1");
				response.setHeader("Content-disposition", "attachment;filename=" + name);
				response.setContentType("application/x-msdownload");
				if(is != null) {
					bis = new BufferedInputStream(is);
					bos = new BufferedOutputStream(response.getOutputStream());
					byte[] buff = new byte[2048];
					int bytesRead;
					while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
						bos.write(buff, 0, bytesRead);
					}
					
				}
				

		}catch(Exception e){
			
		}finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}
	
	}
	
}
